#ifndef CHESS_LOGIC_H
#define CHESS_LOGIC_H

#include <stdbool.h>
#include <ctype.h>
#include <unistd.h>

// 棋子类型定义
#define EMPTY ' '
#define WHITE_PAWN 'P'
#define WHITE_ROOK 'R'
#define WHITE_KNIGHT 'N'
#define WHITE_BISHOP 'B'
#define WHITE_QUEEN 'Q'
#define WHITE_KING 'K'
#define BLACK_PAWN 'p'
#define BLACK_ROOK 'r'
#define BLACK_KNIGHT 'n'
#define BLACK_BISHOP 'b'
#define BLACK_QUEEN 'q'
#define BLACK_KING 'k'

// 移动结构体
typedef struct {
    int from_row;
    int from_col;
    int to_row;
    int to_col;
    int score; // 移动评分
} Move;

// 游戏状态
typedef struct {
    char board[8][8];
    bool white_to_move;
    bool white_can_castle_kingside;
    bool white_can_castle_queenside;
    bool black_can_castle_kingside;
    bool black_can_castle_queenside;
    char opponent_name[32];
    int opponent_elo;
    int opponent_id;
    int en_passant_target; // 存储可以吃过路兵的列（-1表示没有）
    int halfmove_clock;    // 50步规则计数器
    int fullmove_number;
    bool pending_promotion;
    int promote_row;
    int promote_col;
    char promotion_piece; // 升变选择的棋子
    bool white_in_check;
    bool black_in_check;
    bool game_over;
    char winner; // 'W' = 白方胜, 'B' = 黑方胜, 'D' = 平局
    bool player_is_white; // 玩家执白
    bool ai_thinking;    // AI正在思考
    int ai_difficulty;   // AI难度 (1-3)
    Move last_move;      // 最后一步移动
} ChessGame;

// 棋子基础价值
extern const int PIECE_VALUES[256];

// 棋盘初始化
void initialize_board(char board[8][8]);

// 移动验证
bool is_move_valid(ChessGame *game, int from_row, int from_col, int to_row, int to_col);

// 移动执行
void make_move(ChessGame *game, int from_row, int from_col, int to_row, int to_col);

// 状态检查
void update_check_status(ChessGame *game);
bool has_legal_moves(ChessGame *game);
void check_game_over(ChessGame *game);

// AI相关
void ai_move(ChessGame *game);
int evaluate_board(ChessGame *game);

// 攻击检查
bool is_square_attacked(ChessGame *game, int target_row, int target_col, bool by_white);

#endif
